package com.uairobot.bill.tts.agent.controler;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.uairobot.bill.tts.agent.service.PathService;
import com.uairobot.bill.tts.agent.service.TTSService;
import com.uairobot.bill.tts.agent.utils.JaveUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author bill robot
 * @date 2020年1月21日_下午1:46:37 
 * @version 1.0 
 * @desc
 */
@Slf4j
public class ApiAcousticsController extends Controller {
  @Inject
  private TTSService ttss;
  @Inject
  private PathService pathService;

  // api/acoustics/tts?app_key=1234&text=ä½ å¥½ï¼ææ¯äººå·¥æºè½çµè¯ç³»ç»&voice=zhilingf&audio_type=wav
  public void tts() {
	long start = System.currentTimeMillis();
    Kv kv = getKv();
    HashMap<?, ?> params = (HashMap<?, ?>) kv;

    String appKey = (String) params.get("app_key");
    String text = (String) params.get("text");
    String voice = (String) params.get("voice");
    String strRate = (String) params.get("rate");
    Integer rate = Integer.parseInt(strRate);
    voice = "标准合成_甜美女声_楠楠";
    log.info("{},{},{},{}", appKey, text, voice, rate);

    Integer rateId = null;
    if (rate != null) {
      rateId = rate / 8000;
    }

    File wavFolder = pathService.validWavDir();

    String md5Hex = DigestUtils.md5Hex(text); // md5加密
    String mp3Filename = ttss.getFileName(voice, "mp3", 2, md5Hex);
    String mp3FilePath = wavFolder.getAbsolutePath() + File.separator + mp3Filename;
    File mp3File = new File(mp3FilePath);

    String wavFilename = ttss.getFileName(voice, "wav", rateId, md5Hex);
    String wavFilePath = wavFolder.getAbsolutePath() + File.separator + wavFilename;
    File wavFile = new File(wavFilePath);

    if (!wavFile.exists()) { // 文件不存在,合成文件
      if (!mp3File.exists()) {
        ByteArrayOutputStream baos = null;
        Map<String, Object> ttsResult = ttss.tts(text, voice, 3, 2);
        if ("-1".equals(ttsResult.get("code"))) {
          renderJson(ttsResult.get("msg"));
          return;
        } else {
          baos = (ByteArrayOutputStream) ttsResult.get("data");
        }
        try {
          FileUtils.writeByteArrayToFile(mp3File, baos.toByteArray());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      JaveUtil.mp32Wav(mp3FilePath, wavFilePath, rate, 1, rate * 16 * 1);
    }
    log.info("文件合成完成,并返回:{}", wavFilePath);
    renderFile(wavFile);
    long end = System.currentTimeMillis();
    log.info("工经过了:{}ms",end-start);
  }
}
